<template>
	<div class="padding-across-10" v-loading.fullscreen.lock="loading" element-loading-text="拼命加载中">
		<div style="width: 100%">
			<headerOpreate style="float: left" :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
			<el-dropdown style="margin-left: 5px" split-button size="small" type="primary" @command="handleExportExcel">
				导出表格
				<el-dropdown-menu slot="dropdown">
					<el-dropdown-item command="1">
						<i class="el-icon-eleg-icon_table el-icon--left"></i>导出当前
					</el-dropdown-item>
					<el-dropdown-item command="2">
						<i class="el-icon-eleg-icon_table el-icon--left"></i>导出全部
					</el-dropdown-item>
				</el-dropdown-menu>
			</el-dropdown>
			<div style="float: right">
				<span style="font-size: 13px;font-weight: bold">{{$t('message.start')}}</span>
				<el-date-picker :editable="false" v-model="startTime" :clearable="false" size="small" type="date" placeholder="选择起始日期" @change="changeStartTime"></el-date-picker>
				<span style="font-size: 13px;font-weight: bold">{{$t('message.end')}}</span>
				<el-date-picker :editable="false" v-model="endTime" :clearable="false" size="small" type="date" placeholder="选择结束日期" @change="changeEndTime"></el-date-picker>
			</div>
		</div>
		<el-row style="width: 100%;padding: 5px 0;">
			<el-col :span="11">
				<div>
					<span style="font-size: 13px;font-weight: bold">馆藏地</span>
					<el-select size="small" v-model="location" placeholder="暂无数据" style="width: 120px;margin-right: 2px" @change="selectLocation">
						<el-option v-for="item in locationDatas" :key="item.LocationKeyId" :label="item.Name" :value="item.LocationKeyId">
						</el-option>
					</el-select>
					<span style="font-size: 13px;margin-top: 5px;font-weight: bold">检索字段</span>
					<el-select size="small" v-model="value" :placeholder="$t('message.selectModeAlert')" style="width: 85px;margin-right: 2px" @change="selectType">
						<el-option label="关键字" :value="0"></el-option>
						<el-option label="条码" :value="1"></el-option>
						<el-option label="标签" :value="2"></el-option>
					</el-select>
					<span style="font-size: 13px;margin-top: 5px;font-weight: bold">关键字</span>
					<el-autocomplete size="small" style="width: 150px;" class="inline-input" v-model="searchModel" :fetch-suggestions="querySearch" :placeholder="contentHint" @select="handleSelect">
						<el-button id="searchData" slot="append" icon="search" @click="getDatas"></el-button>
					</el-autocomplete>
				</div>
			</el-col>
			<el-col :span="13">
				<div class="block" style="text-align:right;float: right;">
					<el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange" :current-page="currentPage" :page-size="pageSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="totalSize">
					</el-pagination>
				</div>
			</el-col>
		</el-row>
		<el-table border style="width: 100%;" :data="tableData">
			<el-table-column :show-overflow-tooltip="true" type="index" align="center"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="设备码" align="center" prop="DeviceSn"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="读者证号" align="center" prop="ReaderCode"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="书名" align="center" prop="BookName"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="条码" align="center" prop="BookCode"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="标签" align="center" prop="BookTagCode"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="异常时间" align="center" prop="ExceptionTime"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="异常描述" align="center" prop="ExceptionReson">
			</el-table-column>
			<el-table-column :show-overflow-tooltip="true" :label="$t('message.operation')" align="center">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.BorrowOrReturn === 1" type="success">借书</el-tag>
					<el-tag v-else type="warning">还书</el-tag>
				</template>
			</el-table-column>
		</el-table>
		<div class="block" style="text-align:right;margin-bottom:100px">
			<el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange" :current-page="currentPage" :page-size="pageSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="totalSize">
			</el-pagination>
		</div>
	</div>
</template>
<script>
	import $ from 'jquery'
	import { GloabFun, HttpServer } from '../../../../../assets/js/common.js'
	import headerOpreate from '../../../../../components/headerOpreate'
	let id = 1000;
	var date = new Date();
	export default {
		components: {
			headerOpreate
		},
		data() {
			//回车触发查询按钮
			document.onkeydown = function(event) {
				var e = event || window.event;
				if(e && e.keyCode == 13) { //回车键的键值为13
					$("#searchData").click();
				}
			};
			Date.prototype.format = function(format) {
				var date = {
					"M+": this.getMonth() + 1,
					"d+": this.getDate()
				};
				if(/(y+)/i.test(format)) {
					format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
				}
				for(var k in date) {
					if(new RegExp("(" + k + ")").test(format)) {
						format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
							date[k] : ("00" + date[k]).substr(("" + date[k]).length));
					}
				}
				return format;
			}
			return {
				location: null,
				locationDatas: [],
				startTime: new Date((date.getTime() - 3600 * 1000 * 24 * 30)).format('yyyy-MM-dd') + ' 00:00:00',
				endTime: date.format('yyyy-MM-dd') + ' 23:59:59',
				loading: false,
				value: 0,
				contentHint: '书名/作者 查询',
				searchModel: '',
				searchHistory: [],
				item: {},
				currentPage: 1,
				pageSize: 10,
				totalSize: 0,
				tableData: [],
				opreateDatas: [{
					size: "small",
					type: 'primary',
					icon: 'el-icon-eleg-icon_refresh el-icon--left',
					name: '刷新',
					action: 'reloadDatas'
				}]
			}
		},
		props: {
			subArgs: {
				type: Object,
				default: function() {
					return {};
				}
			}
		},
		methods: {
			executeAction(action) {
				if(action) {
					this[action]();
				}
			},
			//导出表格
			handleExportExcel(command) {
				if(command === '1'){
					this.exportExcel();
				}else {
					this.exportAll();
				}
			},
			//导出表格
			exportExcel() {　　　　　　
				require.ensure([], () => {　　　　　　　　
					const {
						export_json_to_excel
					} = require('../../../../../assets/js/vendor/Export2Excel.js');　　　　　　　　
					const tHeader = ['设备码', '读者证号', '书名', '图书条码', '图书标签', '操作类型', '异常时间', '异常描述', '备注'];　　　　　　　　
					const filterVal = ['DeviceSn', 'ReaderCode', 'BookName', 'BookCode', 'BookTagCode', 'Operation', 'ExceptionTime', 'ExceptionReson', '' ];　　　　　　　　
					const list = this.tableData;　　　　　　　　
					const data = this.formatJson(filterVal, list);　　　　　　
					export_json_to_excel(tHeader, data, '借还异常记录');　　　　　　
				})　　　
			},
			exportAll() {
				this.loading = true;
				var param = {
					key: this.value === 0 ? this.searchModel : '',
					bookcode: this.value === 1 ? this.searchModel : '',
					booktag: this.value === 2 ? this.searchModel : '',
					begin: this.startTime,
					end: this.endTime
				}
				HttpServer.httpPost.call(this, '/Api/CirculateException/Info', param, function(response) {}, function(response) {
					this.loading = false;
					// console.log('借还异常信息',response)
					if(response.data.code === 0) {
						response.data.info.forEach(function(item) {
							if(item.BorrowOrReturn === 1) {
								item.Operation = '借书';
							}else {
								item.Operation = '还书';
							}
						})
						this.formateData(response.data.info);
						require.ensure([], () => {　　　　　　　　
							const {
								export_json_to_excel
							} = require('../../../../../assets/js/vendor/Export2Excel.js');　　　　　　　　
							const tHeader = ['设备码', '读者证号', '书名', '图书条码', '图书标签', '操作类型', '异常时间', '异常描述', '备注'];　　　　　　　　
							const filterVal = ['DeviceSn', 'ReaderCode', 'BookName', 'BookCode', 'BookTagCode', 'Operation', 'ExceptionTime', 'ExceptionReson', '' ];　　　　　　　　
							const list = response.data.info;　　　　　　　　
							const data = this.formatJson(filterVal, list);　　　　　　
							export_json_to_excel(tHeader, data, '借还异常记录');　　　　　　
						})
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				})
			},
			formatJson(filterVal, jsonData) {　　　　　　
				return jsonData.map(v => filterVal.map(j => v[j]))　　
			},	
			querySearch(queryString, cb) {
				var restaurants = this.searchHistory;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			},
			createFilter(queryString) {
				return(restaurant) => {
					return(restaurant.value.indexOf(queryString.toLowerCase()) === 0);
				};
			},
			handleSelect(item) {
				// console.log(item);
			},

			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDatas();
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.getDatas();
			},
			//起始时间
			changeStartTime(val) {
				this.startTime = val + ' 00:00:00';
				this.getDatas();
			},
			//结束时间
			changeEndTime(val) {
				this.endTime = val + ' 23:59:59';
				this.getDatas();
			},
			//去掉时间中的T
			formateData(array) {
				for(var i = 0; i < array.length; i++) {
					var index1 = array[i].ExceptionTime.indexOf("T");
					array[i].ExceptionTime = array[i].ExceptionTime.substring(0, index1) + " " + array[i].ExceptionTime.substring(index1 + 1, index1 + 9);
				}
			},
			//选择查询类型
			selectType() {
				if(this.value === 0) {
					this.contentHint = '书名/作者 查询';
				} else if(this.value === 1) {
					this.contentHint = '请输入完整的图书条码';
				} else {
					this.contentHint = '请输入完整的图书标签';
				}
			},
			//刷新
			reloadDatas() {
				this.loading = true;
				var param = {
					key: this.value === 0 ? this.searchModel : '',
					bookcode: this.value === 1 ? this.searchModel : '',
					booktag: this.value === 2 ? this.searchModel : '',
					begin: this.startTime,
					end: this.endTime,
					index: this.currentPage,
					pagesize: this.pageSize,
					locationid: this.location
				}
				HttpServer.httpPost.call(this, '/Api/CirculateException/Info', param, function(response) {}, function(response) {
					this.loading = false;
					// console.log('借还异常信息',response)
					if(response.data.code === 0) {
						response.data.info.forEach(function(item) {
							if(item.BorrowOrReturn === 1) {
								item.Operation = '借书';
							}else {
								item.Operation = '还书';
							}
						})
						this.formateData(response.data.info);
						this.tableData = response.data.info;
						this.totalSize = response.data.total;
						this.$notify({
							title: '成功',
							message: this.$t('message.refreshSuccess'),
							type: 'success',
							duration: 2500
						});
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				})
			},
			selectLocation() {
				this.currentPage = 1;
				this.getDatas();
			},
			//查询用户绑定的馆藏地
			getLocationDatasByUser() {
				HttpServer.httpPost.call(this,'/Api/LibraryLocation/GetByUser',{UserId: parseInt(GloabFun.getKeyId())},function(response){},function(response){
					if(response.data.code === 0){
						response.data.info.unshift(
						{
							Name: '全部',
							LocationKeyId: 0
						}						
						);
						this.locationDatas = response.data.info;
						this.location = this.locationDatas[0].LocationKeyId;
						this.getDatas();
					}else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				})
			},
			//获取数据
			getDatas() {
				//保存至搜索历史
				if(this.searchModel != '') {
					this.item.value = this.searchModel;
					if(JSON.stringify(this.searchHistory).indexOf(JSON.stringify(this.item)) == -1) {
						if(this.searchHistory.length === 7) {
							this.searchHistory.splice(0, 1);
						}
						this.searchHistory.push(this.item);
						GloabFun.setSearchBook(JSON.stringify(this.searchHistory));
						this.$nextTick(function() {
							this.searchHistory = JSON.parse(GloabFun.getSearchBook());
						})
					}
				}
				this.loading = true;
				var param = {
					key: this.value === 0 ? this.searchModel : '',
					bookcode: this.value === 1 ? this.searchModel : '',
					booktag: this.value === 2 ? this.searchModel : '',
					begin: this.startTime,
					end: this.endTime,
					index: this.currentPage,
					pagesize: this.pageSize,
					locationid: this.location
				}
				HttpServer.httpPost.call(this, '/Api/CirculateException/Info', param, function(response) {}, function(response) {
					this.loading = false;
					// console.log('借还异常信息',response)
					if(response.data.code === 0) {
						response.data.info.forEach(function(item) {
							if(item.BorrowOrReturn === 1) {
								item.Operation = '借书';
							}else {
								item.Operation = '还书';
							}
						})
						this.formateData(response.data.info);
						this.tableData = response.data.info;
						this.totalSize = response.data.total;
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				})
			}
		},
		created() {
			var str = GloabFun.getSearchBook();
			if(str != '') {
				this.searchHistory = JSON.parse(str);
			} else {
				this.searchHistory = [];
			}
			this.getLocationDatasByUser();
		}
	}
</script>
<style scoped>
	@import '../../../../../assets/css/font-awesome-4.7.0/css/font-awesome.css';
</style>
<style scoped lang="less">
	.name {
		color: #20a0ff;
	}
	
	.el-date-editor.el-input {
		width: 130px;
	}
	
	.edit-mission {
		padding-top: 50px;
		.el-dialog__header {
			background-color: #000;
		}
		.el-dialog__body {
			position: relative;
		}
		.clearfloat {
			height: 100px;
			max-height: 150px;
		}
	}
</style>